package com.xbongbong.formula.qlexpress.operator.date;

import com.ql.util.express.Operator;
import com.xbongbong.formula.constant.Constant;
import com.xbongbong.paas.toolbox.exception.XbbException;
import com.xbongbong.paas.toolbox.util.DateTimeUtil;
import com.xbongbong.paas.toolbox.util.PaasDateUtil;
import com.xbongbong.pro.enums.ErrorCodeEnum;
import com.xbongbong.pro.enums.errorcodes.BusinessRuleErrorCodeEnum;
import com.xbongbong.saas.constant.BasicConstant;
import org.apache.commons.lang3.StringUtils;

import java.time.DayOfWeek;
import java.time.LocalDate;
import java.time.temporal.WeekFields;
import java.util.Objects;

/**
 * 计算一个时间段在某年内的相交天数
 * @author 吴峰
 * @version v1.0
 * @date 2019/8/5 10:47
 * @since v1.0
 */
public class OperatorIsoWeekNum extends Operator {


    public OperatorIsoWeekNum(String name){
        this.name = name;
    }

    public OperatorIsoWeekNum(String aliasName, String aName, String errorInfo){
        this.aliasName = aliasName;
        this.name = aName;
        this.errorInfo = errorInfo;
    }


    /**
     * 周数计算
     * ISOWEEKNUM(timestamp)
     * 返回给定日期在全年中的ISO周数。
     * timestamp: 必需。日期是Excel用于日期和时间计算的日期-时间代码
     * @return
     * @throws Exception
     */
    @Override
    public Object executeInner(Object[] list) throws Exception {
        if (Objects.isNull(list) || list.length != BasicConstant.ONE) {
            throw new XbbException(BusinessRuleErrorCodeEnum.API_ERROR_261007);
        }
        Long time = PaasDateUtil.getInt(list[0]);
        if (list[0] == null || StringUtils.equals(list[0].toString(), Constant.ZERO_STRING)) {
            return null;
        }
        Integer year = DateTimeUtil.getYear4Someday(time);
        Integer month = DateTimeUtil.getMonth4Someday(time);
        Integer day = DateTimeUtil.getDay4Someday(time);
        LocalDate localDate1 = LocalDate.of(year, month, day);
        WeekFields weekFields = WeekFields.of(DayOfWeek.MONDAY,4);
        return localDate1.get(weekFields.weekOfWeekBasedYear());
    }
}
